// pages/act/actApply/actApply.js
let {
  api_GetActApplyForm,
  api_ApplyNewAct,
  api_uc_GetInfoByToken,
  api_SendTemplateMessage
} = require("../../api/getData.js")
import {
  $wuxToptips
} from '../../components/wux-index'
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // popShow: false,
    // isAssignAcademy: false,
    // canAssignAcademy: false,
    // agreeFlag: false,
    // assignedAcademies: [], //院系限制
    // departNum: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
    // departName: ['1系', '2系', '3系', '4系', '5系', '6系', '7系', '8系', '9系', '10系', '11系', '12系', '13系', '14系', '15系', '16系', '17系', '18系',
    //     '19系', '20系', '21系', '22系', '23系', '24系', '25系', '26系', '27系', '28系', '29系', '30系',
    // ],
    lengthOfTheme: 0,
    actTypeIndex: 0,
    actTypes: [],
    domainTypes: [],
    domainIndex: 0,
    ifTeacher: ['是', '否'],
    ifTeacherIndex: 1,
    startdate: '2018-09-01',
    starttime: '12:00',
    enddate: '2018-09-01',
    endtime: '12:00',
    commitment: [{
      name: "yes",
      value: "我同意活动发起承诺书"
    }],
    guestNum: 0, //主讲人数
    buttonDisabled: true, //提交按钮状态
    maxNum: 8, //最大参与人数
    // checked: true,
    // timeValidate: true,


    //待提交的表单数据
    title: '', //活动标题
    actType: '微沙龙', //活动类型
    domains: [], //学科方向
    place: '', //活动地点
    maxQuantity: 3, // 可参与人数
    hasTeacher: false, // 教师参与
    summary: '', //活动简介
    speakers: [], //主讲人
    contactEmail: '',
    contactName: '',
    contactTel: '',
    cardHasSeat: false, // 是否含有座位信息
    cardSeatInfo: '', // 座位信息
    cardTitle: '',
    cardCanGive: false,
    cardGetLimit: 1,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    /*获取活动类型和学科方向*/
    api_GetActApplyForm((res) => {
      console.log("#########--发起活动表单--##########", res.data.data)
      let tmp1 = []
      let tmp2 = ['自定义']
      res.data.data.actTypes.forEach(i => {
        tmp1.push(i.name)
      })
      res.data.data.domains.forEach(i => {
        tmp2.push(i.name)
      })
      this.setData({
        actTypes: tmp1,
        domainTypes: tmp2,
        _startdate: app.timePicker.date,
        startdate: app.timePicker.date,
        starttime: app.timePicker.time,
        enddate: app.timePicker.date,
        endtime: app.timePicker.time,
      })
    })
    /*通过token获取用户信息*/
    api_uc_GetInfoByToken((res) => {
      console.log('通过token获取用户信息==>', res.data.data)
      this.setData({
        contactEmail: res.data.data.email,
        contactName: res.data.data.nickname,
        contactTel: res.data.data.phone
      })
    })
  },

  // 活动主题长度
  getLengthOfTheme: function(e) {
    var length = e.detail.value.length;
    this.setData({
      lengthOfTheme: length
    })
  },
  //活动主题设置
  setActFormTitle: function(e) {
    this.setData({
      title: e.detail.value
    })
  },
  //活动类型改变
  actTypeChange: function(e) {
    this.setData({
      actTypeIndex: e.detail.value,
      actType: this.data.actTypes[e.detail.value]
    })
    if (this.data.actType !== "微沙龙") {
      this.setData({
        maxNum: 2000
      })
    } else if (this.data.hasTeacher == true) {
      this.setData({
        maxNum: 12
      })
    } else {
      this.setData({
        maxNum: 8
      })
    }
  },
  //学科方向设置
  domainTypeChange: function(e) {
    let tmp = []
    tmp.push(this.data.domainTypes[e.detail.value])
    this.setData({
      domainIndex: e.detail.value,
      domains: tmp
    })
  },
  //学科方向自定义
  setUserDefineddomain: function(e) {
    let str = 'domains[0]'
    this.setData({
      [str]: e.detail.value
    })
  },
  //活动地点设置
  setActFormPlace: function(e) {
    this.setData({
      place: e.detail.value
    })
  },
  //参与人数设置
  setActFormMaxQuantity: function(e) {
    this.setData({
      maxQuantity: e.detail
    })
  },
  //教师参与设置
  ifTeacherChange: function(e) {
    console.log('设置教师参与', e.detail)
    if (e.detail == true) {
      this.setData({
        maxNum: 12
      })
    }
    this.setData({
      hasTeacher: e.detail
    });
  },

  //活动简介长度
  getLengthOfInfo: function(e) {
    var length = e.detail.value.length;
    this.setData({
      lengthOfInfo: length
    })
  },
  //活动简介设置
  setActFormSummary: function(e) {
    this.setData({
      summary: e.detail.value
    })
  },
  //设置活动开始时间
  bindDateChange1: function(e) {
    // console.log('startDate++++++++++++++++++++++',e)
    this.setData({
      startdate: e.detail.value
    })
  },
  bindTimeChange1: function(e) {
    this.setData({
      _starttime: e.detail.value,
      starttime: e.detail.value
    })
  },
  // 设置活动结束时间
  // bindDateChange2: function(e) {
  //   this.setData({
  //     enddate: e.detail.value
  //   })
  // },
  bindTimeChange2: function(e) {
    this.setData({
      endtime: e.detail.value
    })
  },
  //更改主讲人数
  changeGuestNum: function(e) {
    let tmp = []
    for (let i = 0; i < e.detail; i++) {
      // console.log('//////////////////////////////////////',i)
      tmp.push({
        index: i,
        name: '',
        studentId: '',
        summary: ''
      })
    }
    this.setData({
      speakers: tmp
    })
  },
  //设置主讲人姓名
  setSpeakerName: function(e) {
    console.log('输入值==>', e.detail.value)
    console.log('speaker定位==>', e.currentTarget.dataset.index)
    let index = e.currentTarget.dataset.index
    let name = e.detail.value
    let str = 'speakers[' + index + '].name'
    this.setData({
      [str]: name
    })
  },
  //设置主讲人学工号
  setSpeakerStudentId: function(e) {
    console.log('输入值==>', e.detail.value)
    console.log('speaker定位==>', e.currentTarget.dataset.index)
    let index = e.currentTarget.dataset.index
    let studentid = e.detail.value
    let str = 'speakers[' + index + '].studentId'
    this.setData({
      [str]: studentid
    })
  },
  //设置主讲人简介
  setSpeakerSummary: function(e) {
    console.log('输入值==>', e.detail.value)
    console.log('speaker定位==>', e.currentTarget.dataset.index)
    let index = e.currentTarget.dataset.index
    let summary = e.detail.value
    let str = 'speakers[' + index + '].summary'
    this.setData({
      [str]: summary
    })
  },



  //活动发起承诺书弹窗
  checkboxChange: function(e) {
    console.log('checkbox发生change事件，携带value值为：', e.detail.value)
    if (e.detail.value.length == 1) {
      this.setData({
        buttonDisabled: false
      })
      wx.showModal({
        title: '活动发起承诺书',
        content: '我承诺，本次活动是以学术交流为目的，主题积极向上。我将严格遵守《用户协议》，保证活动内容不涉及政治、宗教、性别歧视、地域歧视或种族歧视等违法违规事项。如有违反任何法律法规及相关条款，本人愿意承担所有责任。',
        showCancel: false,
        confirmText: "了解了"
      })
    } else {
      this.setData({
        buttonDisabled: true
      })
    }
  },

  //提交发起活动表单
  submitApply: function(e) {
    console.log('formId==>', e.detail.formId)
    //发起活动前数据的处理与验证
    var _this = this
    let that = this.data
    let form = {
      title: that.title, //活动主题
      actType: that.actType, //活动类型
      domains: that.domains, //学科方向
      startTime: that.startdate + ' ' + that.starttime, //开始时间
      endTime: that.startdate + ' ' + that.endtime, //结束时间
      place: that.place, //活动地点
      maxQuantity: that.maxQuantity, // 可参与人数
      hasTeacher: that.hasTeacher, // 教师参与
      summary: that.summary, //活动简介
      speakers: that.speakers, //主讲人
      contactEmail: that.contactEmail,
      contactName: that.contactName,
      contactTel: that.contactTel,
      cardHasSeat: that.cardHasSeat, // 是否含有座位信息
      cardSeatInfo: that.cardSeatInfo, // 座位信息
      cardTitle: that.cardTitle,
      cardCanGive: that.cardCanGive,
      cardGetLimit: that.cardGetLimit,
      // assignedAcademies: '', //限制院系
    }
    console.log('发起活动前组装成的表单==>', form)
    ///////////////////////////////////////////////表单验证
    if (form.title.length == 0) {
      $wuxToptips().show({
        icon: 'cancel',
        hidden: false,
        text: '活动标题不能为空',
        duration: 2000,
        success() {},
      })
    } else if (form.domains.length == 0) {
      $wuxToptips().show({
        icon: 'cancel',
        hidden: false,
        text: '学科方向不能为空',
        duration: 2000,
        success() {},
      })
    } else if (form.place.length == 0) {
      $wuxToptips().show({
        icon: 'cancel',
        hidden: false,
        text: '活动地点不能为空',
        duration: 2000,
        success() {},
      })

    } else if (form.summary.length == 0) {
      $wuxToptips().show({
        icon: 'cancel',
        hidden: false,
        text: '活动简介不能为空',
        duration: 2000,
        success() {},
      })
    } else {
      // let st = form.startTime.substring(11,16);
      // let et = form.endTime.substring(11, 16);
      // let cuttime = (Date.parse(et) - Date.parse(st)) / 86400000 * 24;
      // console.log('+++++++++++++++++++++++++++++++++', et)
      // console.log('+++++++++++++++++++++++++++++++++', st)
      // console.log('+++++++++++++++++++++++++++++++++',cuttime)
      let st = new Date(form.startTime);
      let et = new Date(form.endTime);
      let cuttime = (Date.parse(et) - Date.parse(st)) / 86400000 * 24;
      console.log('+++++++++++++++++++++++++++++++++', st)
      console.log('+++++++++++++++++++++++++++++++++', et)
      console.log('+++++++++++++++++++++++++++++++++', cuttime)
      if (cuttime < 1) {
        $wuxToptips().show({
          icon: 'cancel',
          hidden: false,
          text: '活动时间不能低于1小时',
          duration: 2000,
          success() {},
        })
      }else{ 
      ////////////////////////////////////////////////
      let formJsonStr = JSON.stringify(form);
      console.log('转换后的json字符串==>', formJsonStr);
      this.setData({
        formJsonStr: formJsonStr,
        formId: e.detail.formId
      })
      let tmp = this.data.formJsonStr

      wx.showModal({
        title: '确认发起此活动？',
        success: function(res) {
          if (res.confirm) {
            console.log('用户点击确定发起活动')
            let formData = 'actApplyFormJsonStr='
            formData += tmp
            console.log('活动提交表单数据==> ', formData)
            //调用发起活动API
            api_ApplyNewAct(formData, (res) => {
              console.log('活动发起结果==>', res)
              if (res.errmsg == "ok") {
                //发送模板消息
                _this.sendTemplateMessage()

                //发起成功弹窗提示
                wx.showModal({
                  title: '发起成功',
                  content: res.data,
                })
                // setTimeout(function() {
                //   wx.switchTab({
                //     url: '../home/home',
                //   })
                // }, 1500)
              } else {
                wx.showModal({
                  title: '失败',
                  content: '请尝试重新发起',
                  success: function(res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                    } else if (res.cancel) {
                      console.log('用户点击取消')
                    }
                  }
                })
              }
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      } // if time>1
    } //else
  },
  //提交成功发送模板消息
  sendTemplateMessage: function(e) {
    // 模板消息关键词参数
    let keywords = {
      "keyword1": {
        "value": "同研开发者测试",
        "color": "#173177"
      },
      "keyword2": {
        "value": "英语微沙龙",
        "color": "#173177"
      },
      "keyword3": {
        "value": "英语",
        "color": "#173177"
      },
      "keyword4": {
        "value": "新主楼",
        "color": "#173177"
      },
      "keyword5": {
        "value": "2018-10-04 19:00-21:00",
        "color": "#173177"
      },
    }
    let data = JSON.stringify(keywords);
    let messageData = {
      templateId: 'TkJVwatplFTVp0ZvsHRcfeugqpm1nq_f_qBekHA6Bzo',
      page: '/pages/act/home/home',
      formId: this.data.formId,
      data: data,
      // color: "#173177",
    }
    console.log('==>待发送的模板消息数据：', messageData)
    //调用发送模板消息API
    api_SendTemplateMessage(messageData, (res) => {
      console.log('发送模板消息==>', res)
    })
  }

})